package com.cloud.workTest;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MappingJsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JsonParserTest {
    public static void main(String[] args) throws Exception {

        String filePath = "C:\\Users\\86159\\Desktop\\prometheus.json";
        try {
            // 读取原始JSON文件内容
            String originalJson = readJsonFile(filePath);

            // 使用JsonFactory和JsonParser逐行解析原始JSON内容
            JsonFactory jsonFactory = new JsonFactory();
            JsonParser jsonParser = jsonFactory.createParser(originalJson);

            // 创建一个StringBuilder以保存修改后的JSON内容
            StringBuilder updatedJson = new StringBuilder();

            ObjectMapper objectMapper = new ObjectMapper();

            while (jsonParser.nextToken() != null) {
                // 使用JsonNode来解析JSON对象
                JsonNode jsonNode = objectMapper.readTree(jsonParser);

                // 在这里进行需要的修改
                if (jsonNode.get("labels").get("node_hostname").asText().equals("node1_host")) {
                    ArrayNode arrayNode = ((ObjectNode) jsonNode).putArray("targets");
                    arrayNode.add("node-exporter0:9101");
                }

                // 将修改后的对象转换回JSON字符串并添加到StringBuilder
                updatedJson.append(objectMapper.writeValueAsString(jsonNode));
                updatedJson.append(System.lineSeparator()); // 添加换行符
            }

            // 将修改后的JSON内容写回原始文件
            writeJsonToFile(filePath, updatedJson.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String readJsonFile(String fileName) throws IOException {
        // 读取文件内容到字符串
        StringBuilder content = new StringBuilder();
        try (FileReader fileReader = new FileReader(fileName)) {
            int character;
            while ((character = fileReader.read()) != -1) {
                content.append((char) character);
            }
        }
        return content.toString();
    }

    private static void writeJsonToFile(String fileName, String content) throws IOException {
        // 将字符串内容写入文件
        try (FileWriter fileWriter = new FileWriter(fileName)) {
            fileWriter.write(content);
        }
    }
}
